#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define CH_MAX 100

char *filename = "wordbook.txt";

char *statname = "wordbook_stat.txt";

int _put(FILE *, char * const *, int n);

int get(FILE *, const char *);

int list(FILE *);

FILE * open(FILE **, const char *);

int plus_num(int);

int update_stat(FILE *);

int main(int argc, char **argv)
{
    FILE * fp;

    if (argc < 2) {
        open(&fp, "r");
        list(fp);

    } else if (argc < 3) {
        open(&fp, "r");
        if (strcmp(*++argv, "--update") == 0) {

            int num = update_stat(fp);

            if (num >-1)
                printf("更新了%d个文件.\n", num);

        } else {
            get(fp, *argv);
        }


    } else {
        open(&fp, "a+");

        --argc;
        argc -= argc % 2;
        _put(fp, ++argv, argc);
    }

    fclose(fp);

    return 0;
}

FILE * open(FILE ** fp, const char * flag)
{
    if ((*fp = fopen(filename, flag)) == NULL) {
        fprintf(stderr, "文件%s打开失败.\n", filename);
        exit(1);
    }

    return *fp;
}

int _put(FILE * fp, char * const * list, int n)
{
    int base = 0;
    char *en;
    char *ch;

    while (n > 0) {
        en = *list++;
        ch = *list++;

        if (fprintf(fp, "%s %s\n", en, ch) < 0) {
            fprintf(stderr, "写入单词失败 [%s %s]\n", en, ch);
            break;
        }

        n-=2;
        ++base;
    }

    if (base)
        plus_num(base);


    return 0;
}

int plus_num(int base)
{
    FILE * fp;
    int num = 0;

    if ((fp = fopen(statname, "r+")) != NULL) {
        fscanf(fp, "%d", &num);
        rewind(fp);
        fprintf(fp, "%d\n", num + base);

    } else {
        fprintf(stderr, "文件%s写入失败.", statname);
        exit(1);
    }

    return num+base;
}

int update_stat(FILE * fp)
{
    int num = 0;
    char ch;

    while ((ch=fgetc(fp)) != EOF)
        if (ch == '\n')
            ++num;

    if ((fp = fopen(statname, "w")) != NULL) {
        fprintf(fp, "%d", num);

    } else {
        fprintf(stderr, "文件%s写入失败.", statname);
        return -1;
    }

    return num;
}



int get(FILE * fp, const char * ens)
{
    char en[127];
    char ch[127];

    int res = -1;

    while ((fscanf(fp, "%s%s", en, ch)) > 1) {
        if (0 == strcmp(en, ens)) {
            printf("%s", ch);
            ++res;
            break;
        }
    }

    if (res < 0) {
        printf("该单词不存在.\n");
    }

        return 0;
    }

    int list(FILE * fp)
    {
        char en[127];
        char ch[127];

        while ((fscanf(fp, "%s%s", en, ch)) > 1) {
            printf("%s %s\n", en, ch);
        }

        return 0;
    }
